package com.kaesar.leetcode.LeetCode_201_250;

import com.kaesar.leetcode.ListNode;

import java.util.Stack;

public class LeetCode_234 {
    public static boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true;
        }
        ListNode cur = head;
        // 链表节点的个数
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        // 将前面的一半节点放入栈中
        Stack<Integer> temp = new Stack<>();
        ListNode newCur = head;
        for (int i = 1; i <= count / 2; i++) {
            temp.push(newCur.val);
            newCur = newCur.next;
        }
        int start;
        if (count % 2 == 0) {
            start = count / 2 + 1;
        } else {
            start = count / 2 + 2;
            newCur = newCur.next;
        }
        for (int i = start; i <= count; i++) {
            if (temp.pop() != newCur.val) {
                return false;
            }
            newCur = newCur.next;
        }

        return true;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(0);
        head.next.next = new ListNode(1);

        System.out.println(isPalindrome(head));
    }
}
